<template>
  <div class="img-loader-wp">

    <!--插件形式，直接走服务端api-->
    <template v-if="server">
      <el-upload class="uploader-wp"
         name="file"
         accept="image/gif,image/jpeg,image/jpg,image/png"
         :action="serverUrl"
         :headers="headers"
         :data="data"
         :multiple="false"
         :show-file-list="false"
         :before-upload="beforeUpload"
         :on-success="handleSuccess"
         :on-error="handleError"
         :on-progress="handleProgress"
         :auto-upload="true"
                  >
        <img v-if="url || curl" :src="url || curl" class="uploader-img">
        <i v-if="!url && !curl" class="el-icon-plus uploader-icon"></i>
      </el-upload>
    </template>

    <!--原生模式，可走oss，也可走服务端api，比较灵活-->
    <template v-if="!server">
      <div class="uploader-wp">
        <div class="img-wp" @click.stop.prevent="openFileSelect">
          <img v-if="url || curl" :src="url || curl" class="uploader-img" />
          <span v-if="!url && !curl" class="el-icon-plus uploader-icon"></span>
        </div>

        <input ref="fileInput" class="file-input" type="file" name="file"
               accept="image/gif,image/jpeg,image/jpg,image/png"
               @change="manualUpload" style="display: none;"/>
      </div>
    </template>
  </div>
</template>

<script>
  import {host, osshost} from '@/api/util/fetch';

  export default {
    name: 'img-loader',
    props:{
      img:{
        type:String,
        default:'',
      },
      dir:{
        type:String,
        default:'default',
      },
      maxSize:{ //最大上传限制,默认5m
        type:Number,
        default:5242880,
      },
      update:{ //上传成功后是否更新本地图片地址
        type:Boolean,
        default:false,
      }
    },
    data()
    {
      return {
        url:this.img,
        /*以下是服务端，走的是插件*/

        server:true, //走服务器端还是直接走oss-sdk
        serverUrl:host + 'aliFileUpload/imgFileUpload/' + this.dir, //服务器图片上传地址
        headers:{ //服务器接口需要传递token
          'token':this.$store.getters.token,
        },
        data:{ //request data
        },
        file:{}, //选中的文件
      }
    },
    computed:{
      curl() //解决prop参数传入不能实时bug
      {
        return this.img;
      }
    },
    mounted()
    {
    },
    methods: {
      beforeUpload(file)
      {
        console.log(file);
        let maxSize = this.maxSize;
        if(file.size > maxSize)
        {
          let limit = '';
          if(maxSize >= 1048576)
          {
            limit = (maxSize/1024/1024).toFixed(0) + 'MB';
          }
          else if(maxSize >= 1024)
          {
            limit = (maxSize/1024).toFixed(0) + 'KB';
          }
          else
          {
            limit = maxSize + 'B';
          }

          this.$message({
            message: '超过最大上传限制'+limit,
            type: 'warning'
          });
          return false;
        }

        return true;
      },
      handleSuccess(res, file) {
        if(res.code !==200)
        {
          this.handleError(res,file);
        }
        else
        {
          let relative_url = res.data; //相对路径
          let url = osshost + res.data; //完整地址

          if(this.update)
          {
            this.url = url;
            this.relative_url=relative_url;
          }
          this.$emit('upload-success',{url:url,'relative_url':relative_url});
        }

      },
      handleError(err,file)
      {
        //console.log(err);
        this.$message({
          message: err.message,
          type: 'error'
        });
      },
      handleProgress(event,file)
      {

      },
      openFileSelect() //打开文件选择器
      {
        this.$refs['fileInput'].click();
      },
      manualUpload(e) //手动上传
      {
        //console.log('手动上传');
        let file = e.target.files[0];
        this.file = file;


        if(this.beforeUpload(file))
        {
          let payload = {
            file:file,
            type:this.dir,
            progress:function (p) {
              return function (done) {
               // console.log(p); // 0-1, p*100 + '%'
                done();
              };
            }
          };

          /*走oss sdk直传*/
          this.$store.dispatch('uploadFile',payload).then(resp=>{
            //console.log(resp);
            let res = {
              code:200,
              data:resp.name,
            };

            this.handleSuccess(res,file);

          }).catch(err=>{
            console.log(err);
            this.handleError({message:'图片上传失败，请稍后重试'});
          });

          /*直走server*/
          /*this.$store.dispatch('uploadFileServer',payload).then(resp=>{
            this.handleSuccess(resp,file);

          }).catch(err=>{
            //console.log(err);
            this.handleError(err,file);
          });*/
        }

      },
    }
  }
</script>

<style lang="scss" scoped>
  .img-loader-wp
  {
    width: 100px;
    height: 100px;
    border: 1px dashed #d1dbe5;
    overflow: hidden;

    .uploader-wp
    {
      position: relative;
      width: 100%;
      height: 100%;
      border-radius: 6px;
      overflow: hidden;
      cursor: pointer;
      text-align: center;

      .uploader-img
      {
        position: absolute;
        display: block;
        width: 100%;
        height: 100%;
        top: 0;
        left: 0;
        text-align: center;
      }

      .uploader-icon
      {
        position: absolute;
        font-size: 26px;
        color: #8c939d;
        left: 0;
        top: 0;
        width: 100%;
        height: 100%;

        &:before
        {
          display: inline-block;
          vertical-align: middle;
        }

        &:after
        {
          content: "";
          display: inline-block;
          height: 100%;
          vertical-align: middle;
        }
      }

    }

    &:hover
    {
      border-color: #20a0ff;

      .uploader-wp
      {
        .uploader-icon
        {
          color: #20a0ff;
        }
      }

    }
  }
</style>